//
//  ZYTagViewLayout.m
//  AudientList
//
//  Created by zhangweiwei on 16/6/15.
//  Copyright © 2016年 Erica. All rights reserved.
//

#import "ZYTagViewLayout.h"

@implementation ZYTagViewLayout

- (void)prepareLayout
{
    [super prepareLayout];
    
    self.minimumLineSpacing = 5;
    self.minimumInteritemSpacing = 5;
    
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect
{
    NSArray *attributes = [super layoutAttributesForElementsInRect:rect];
    
    for(int i = 1; i < [attributes count]; ++i) {
        //当前attributes
        UICollectionViewLayoutAttributes *currentLayoutAttributes = attributes[i];
        //上一个attributes
        UICollectionViewLayoutAttributes *prevLayoutAttributes = attributes[i - 1];
        //我们想设置的最大间距，可根据需要改
        NSInteger maximumSpacing = self.minimumInteritemSpacing;
        //前一个cell的最右边
        NSInteger origin = CGRectGetMaxX(prevLayoutAttributes.frame);
        //如果当前一个cell的最右边加上我们想要的间距加上当前cell的宽度依然在contentSize中，我们改变当前cell的原点位置
        //不加这个判断的后果是，UICollectionView只显示一行，原因是下面所有cell的x值都被加到第一行最后一个元素的后面了
        CGRect frame = currentLayoutAttributes.frame;
        if(origin + maximumSpacing + currentLayoutAttributes.frame.size.width < self.collectionViewContentSize.width) {
            frame.origin.x = origin + maximumSpacing;
        }else {
            
            frame.origin.y = CGRectGetMaxY(prevLayoutAttributes.frame) + maximumSpacing;
        }
        currentLayoutAttributes.frame = frame;
    }
    
    return attributes;
}

@end
